﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using WikiPlex.Common;
using WikiPlex.Contrib.Services;

namespace WikiPlex.Contrib
{
    public class Runner
    {
        private readonly IFileSystemService fileSystem;
        private readonly IWikiEngine wikiEngine;
        private static readonly Regex templateRegex = new Regex(@"(?i)<wiki:content\s*/>", RegexOptions.Compiled);

        public Runner() : this(new FileSystemService(), new WikiEngine())
        {
        }

        public Runner(IFileSystemService fileSystem, IWikiEngine wikiEngine)
        {
            this.fileSystem = fileSystem;
            this.wikiEngine = wikiEngine;
        }

        public bool Execute(IEnumerable<string> sourceFiles, string outputDir, string templateFile)
        {
            Guard.NotNullOrEmpty(outputDir, "outputDir");

            bool allCreated = true;
            string template = GetTemplate(templateFile);

            foreach (string file in sourceFiles)
            {
                try
                {
                    string newFilePath = GetOutputFilename(outputDir, file);

                    fileSystem.CreateDirectory(outputDir);

                    string wikiContent = fileSystem.ReadAllText(file);
                    string renderedContent = wikiEngine.Render(wikiContent);
                    fileSystem.WriteAllText(newFilePath, templateRegex.Replace(template, renderedContent));
                }
                catch (Exception)
                {
                    allCreated = false;
                }
            }

            return allCreated;
        }

        private string GetTemplate(string templateFile)
        {
            string template = "<html><body><wiki:content /></body></html>";
            if (fileSystem.FileExists(templateFile))
                template = fileSystem.ReadAllText(templateFile);

            return template;
        }

        private static string GetOutputFilename(string outputFullPath, string file)
        {
            file = Path.GetFileNameWithoutExtension(file) + ".html";
            return Path.Combine(outputFullPath, file);
        }
    }
}